<?php
namespace control;
// 固定资产归还
class assetReturnClass extends adIndexClass
{
    private const page  = 'assetReturn'; # 权限
    private const table = 'asset_use'; # 数据表
    private const tableMx = 'asset_use_detail'; # 子表
    private const title = '固定资产归还';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'receiver'          => [
                        'name'  => "领用人",
                        'width' => 200,
                    ],
                    'department'  => [
                        'name'  => '领用人部门',
                        'width' => 150,
                    ],
                    'receivingDate'         => [
                        'name'  => '领用日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'orderNo'          => [
                        'name'  => '固定资产编码',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '名称',
                        'width' => 150,
                    ],
                    'brand'          => [
                        'name'  => '品牌',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '领用数量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'actualReturn'          => [
                        'name'  => '归还日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "领用单号" => text(array("name" => "orderNo")),
                    "领用人"   => selectMultiple(["name" => "receiver", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    "领用人部门" => selectMultiple([
                        "name"     => "department",
                        'table'   => 'department',
                        'sqlId'=>'id',
                        'sqlField'=>'name',
                        'class' => 'width200',
                    ]),
                ],
                [
                    "领用日期" => text(
                        [
                            'name' => 'receivingDate',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "固定资产编码" => text(array("name" => "cOrderNo")),
                    "名称" => text(array("name" => "name")),
                ],
                [
                    "品牌" => text(array("name" => "brand")),
                    "规格型号" => text(array("name" => "model")),
                    "状态" => select(["name" => "state", 'option' => ['待归还', '超期未还', '已归还']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*固定资产入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= spanButton([
                'fun' => 'operate',
                'name' => '归还',
                'para' => [
                    'act' => 'return',
                    'state' => '归还',
                ]
            ]);
        }
        if ($this->power(self::page, "edit")) {
            $button .= spanButton([
                'fun' => 'operate',
                'name' => '取消归还',
                'para' => [
                    'act' => 'return',
                    'state' => '取消归还',
                ]
            ]);
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*固定资产列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $where   .= search([
            "=" => [
                'coid'=>self::$coid,
                'state' => $this->post('state'),
            ]
        ]);
        //主表查询
        $mwhere   = search([
            "like" => [
                'orderNo'    => $this->post('orderNo'),
                'department' => $this->post('department'),
                'stid'       => $this->post('stid'),
            ],
            "=" => [
                'state' => '已通过',
            ]
        ]);
        if ($this->post('receivingDate')) {
            $mwhere .= self::timeComparison($this->post('receivingDate'), 'date', 'receivingDate');
        }
        if ($mwhere) {
            $where .= " AND orderId IN (SELECT id FROM " . self::table . " WHERE  1=1 $mwhere) ";
        }
        // 子查询
        $cWhere  = search(["like" => [
            'orderNo' => $this->post('cOrderNo'),
            'name'    => $this->post('name'),
            'brand'   => $this->post('brand'),
            'model'   => $this->post('model'),
        ]]);
        if ($cWhere) {
            $where .= " AND atid IN (SELECT id FROM `asset` WHERE  1=1 $cWhere) ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::tableMx, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            $info = query(self::table, " id = '{$array['orderId']}' ");
            $asset = query('asset', " id = '{$array['atid']}' ");
            //列表控件
            $dominate  = array(
                "box" => ["name" => "listId", "value" => $array['id']],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'receiver':
                        $row[] = self::findStaff($info['receiver']);
                        break;
                    case 'department':
                    case 'receivingDate':
                        $row[] = self::findStaff($info[$key]);
                        break;
                    case 'orderNo':
                    case 'name':
                    case 'brand':
                    case 'model':
                        $row[] = $asset[$key];
                        break;
                    case 'actualReturn':
                        $row[] = self::null($array['actualReturn']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $title = $power = $word = '';
        $append = [];
        switch ($act) {
            case 'return':
                $act = 'edit';
                $msg = self::title . '修改状态';
                $function = 'changeState';
                $form = self::page . 'OperateForm, listForm';
                $state = $this->post('state');
                if ($state == '归还') {
                    $append = [
                        must . '选择归还日期：'  => text([
                            "name"     => "actualReturn",
                            "title"    => "归还日期：",
                            'laydate'  => []
                        ]) . hidden(["name"  => "state", 'value' => $state]) . space
                    ];
                } else {
                    $title = self::page . 'Change';
                    $append = [
                        1 => hidden(["name"  => "state", 'value' => $state])
                    ];
                }
                break;
            default:
                // $act = 'del';
                // $msg = '删除'.self::title;
                // $title = self::page.'Delete';
                // $function = 'isDelete';
                // $form = self::page.'OperateForm, listForm';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'append'   => $append,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改状态
     */
    public function changeState()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $act = 'edit';
        $json = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = "你没有此权限的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 修改field
            $fieldKey = 'state';
            $rawState = $this->post('state');
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::tableMx, $where);
                if ($info['id']) {
                    if($rawState == '归还'){
                        if ($info['state'] == '已归还'){
                            $text .= "ID【{$id}】，已是归还状态，无法归还" . '<br>';
                            continue;
                        }
                        if(empty($this->post('actualReturn'))){
                            $json['warn'] = '归还日期不能为空';
                            goto resp;
                        }
                    }else if($rawState == '取消归还'){
                        if ($info['state'] == '待归还'){
                            $text .= "ID【{$id}】，待归还状态，无法取消归还" . '<br>';
                            continue;
                        }
                    }
                    $fieldVlaue = ($info['state'] == '待归还') ? '已归还' : '待归还';
                    // 修改状态
                    $json['warn'] = static::update([
                        "table" => self::tableMx,
                        'field' => [
                            $fieldKey    => $fieldVlaue,
                            'actualReturn' => $this->post('actualReturn') ? $this->post('actualReturn') : '0'
                        ],
                        "where" => $where
                    ], false);
                    // 归还记录
                    if ($json['warn'] == '更新成功' && $fieldVlaue == '已归还') {
                        $asset = query('asset', " id = '{$info['atid']}' ");
                        $asset_reg = query('asset_reg',"id = '$asset[regId]'");
                        static::update(array(
                           'table'=>'asset',
                           'field'=>[
                               'state'=>'在库',
                               'departmentId'=>$asset_reg['keepDeptId'],
                               'userDepartment'=>departmentClass::getTypeName($asset_reg['keepDeptId']),
                               'user'=>'',
                               'unused'=>'是'
                           ],
                            'where'=>"id = '$info[atid]'"
                        ));
                        static::insert([
                            'table' => 'asset_revert',
                            'field' => [
                                'id'             => self::getNo(),
                                'coid'=>self::$coid,
                                'atid'           => $id,
                                'type'           => '归还',
                                'userDepartment' => self::findStaffDepartment($asset['userDepartment']),
                                'user'           => self::findStaff($asset['user']),
                                'storage'        => $info['storage'],
                            ], false
                        ]);
                    }
                    //添加记录
                    $text .= "{$this->control['name']}变更" . self::title . "，ID【{$id}】,状态【{$fieldVlaue}】" . '<br>';
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "操作了{$x}条" . self::title;
            $json['warn']     = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }
}
